<template>
  <div class="container">
    <!-- 学员课程 按钮部分 -->
    <div class="handle-box">
      <el-button-group class="ml-4">
        <el-button type="primary" @click="addCourse">添加课程</el-button>
      </el-button-group>
    </div>
    <el-divider></el-divider>
    <!-- 课程列表 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="courseId" label="课程ID" width="120" show-overflow-tooltip />
      <el-table-column prop="courseName" label="课程名称" min-width="140" show-overflow-tooltip />
      <el-table-column prop="courseType" label="课程类型" width="100" />
      <el-table-column prop="level" label="课程级别" width="90" />
      <el-table-column prop="description" label="课程简介" min-width="180" show-overflow-tooltip />
      <el-table-column prop="totalHours" label="总课时" width="80" />
      <el-table-column prop="classroom" label="教室" width="100" />
      <el-table-column prop="maxStudents" label="最大学员数" width="100" />
      <el-table-column prop="currentStudents" label="已报学员数" width="110" />
      <el-table-column prop="status" label="状态" width="90" show-overflow-tooltip>
        <template #default="scope">
          <el-tag :type="scope.row.status ? 'success' : 'info'">
            {{ scope.row.status ? '开课中' : '已下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="160" show-overflow-tooltip />
      <el-table-column prop="updateTime" label="更新时间" width="160" show-overflow-tooltip />
      <el-table-column
        label="操作"
        width="180"
        fixed="right"
      >
        <template #default="scope">
          <el-row class="btn-opt">
            <el-button link type="primary" :icon="Edit" size="small" @click="editCourse(scope.row)">编辑</el-button>
            <el-button link type="danger" :icon="CloseBold" size="small" @click="deleteCourse(scope.row)">删除</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-row style="margin-top: 30px;">
      <el-col :span="20">
        <el-pagination
          :current-page="pageData.pageCurrent"
          :page-size="pageData.pageSize"
          layout="prev, pager, next"
          :total="pageData.pageTotal"
          background
          @current-change="handleCurrentChange"
        />
      </el-col>
    </el-row>

    <!-- 添加/修改课程抽屉 -->
    <el-drawer v-model="addEditDrawer" direction="rtl" size="50%">
      <template #header>
        <h2>{{ drawerTitle }}</h2>
      </template>
      <AddEditCourse
        :courseFormData="courseFormData"
        :drawerTitle="drawerTitle"
        @save="handleSave"
        @cancel="addEditDrawer = false"
      />
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import axios from 'axios'
import { Edit, CloseBold } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import AddEditCourse from './courseListSub/AddEditCourse.vue'

const pageData = reactive({
  pageCurrent: 1,
  pageSize: 7,
  pageTotal: 0
})

const tableData = ref([])

const getData = async () => {
  const res = await axios.get('http://localhost:8080/api/courses')
  const all = Array.isArray(res.data) ? res.data : res.data.data
  pageData.pageTotal = all.length
  const start = (pageData.pageCurrent - 1) * pageData.pageSize
  const end = pageData.pageCurrent * pageData.pageSize
  tableData.value = all.slice(start, end)
}

watch(() => pageData.pageCurrent, () => {
  getData()
})

onMounted(() => {
  getData()
})

const handleCurrentChange = (val) => {
  pageData.pageCurrent = val
}

const addEditDrawer = ref(false)
const drawerTitle = ref('')
const courseFormData = ref({})

const addCourse = () => {
  addEditDrawer.value = true
  drawerTitle.value = '新增课程'
  courseFormData.value = {
    courseId: null,
    courseName: '',
    courseType: '',
    level: '',
    description: '',
    totalHours: null,
    classroom: '',
    maxStudents: null,
    currentStudents: null,
    status: true,
    createTime: '',
    updateTime: ''
  }
}

const editCourse = (row) => {
  addEditDrawer.value = true
  drawerTitle.value = '编辑课程'
  // 深拷贝，避免直接修改表格数据
  courseFormData.value = JSON.parse(JSON.stringify(row))
}

const deleteCourse = async (row) => {
  try {
    await ElMessageBox.confirm(
      '你确定要删除此课程吗?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    await axios.delete(`http://localhost:8080/api/courses/${row.courseId}`)
    ElMessage.success('删除成功')
    getData()
  } catch (e) {
    if (e !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleClose = (done) => {
  ElMessageBox.confirm('你确定关闭吗?')
    .then(() => {
      done()
    })
    .catch(() => {
      // catch error
    })
}

const handleSave = async (formData) => {
  try {
    console.log('编辑提交数据:', formData)
    if (drawerTitle.value === '新增课程') {
      await axios.post('http://localhost:8080/api/courses', formData)
      ElMessage.success('添加成功')
    } else {
      await axios.put(`http://localhost:8080/api/courses/${formData.courseId}`, formData)
      ElMessage.success('编辑成功')
    }
    addEditDrawer.value = false
    getData()
  } catch (e) {
    ElMessage.error('操作失败')
  }
}
</script>

<style lang="less" scoped>
.handle-box {
  margin-bottom: 20px;
}
.btn-opt {
  font-size: 13px;
  .el-button {
    margin-left: 3px;
    font-size: 13px;
    padding: 1px 6px;
  }
}
</style>